//
//  YFMapSearchView.m
//  project
//
//  Created by yefei on 2019/4/30.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFMapSearchView.h"
#import "YFLocationManager.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

@interface YFMapSearchView ()<MAMapViewDelegate>

@property (nonatomic, strong) MAMapView *mapView;

@property (nonatomic, strong) MAPointAnnotation *userAnnotation;

@property (nonatomic, strong) MAPointAnnotation *selectedAnnotation;

@property (nonatomic, strong) YFMapSearchModel *resultModel;

/**
 定位蓝点
 */
@property (nonatomic,strong) MAUserLocationRepresentation * represent;
@property (weak, nonatomic) IBOutlet UIButton *locatingButton;

@property (weak, nonatomic) IBOutlet UIButton *ensureButton;


@end

@implementation YFMapSearchView

#pragma mark3 - 绝对单例
static YFMapSearchView *_manager = nil;
+ (instancetype)shared {
    
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [[UINib nibWithNibName:@"YFMapSearchView" bundle:nil] instantiateWithOwner:nil options:nil].firstObject;
        _manager.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGTH - NAVIGATION_BAR_HEIGHT);
    });
    return _manager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}

- (instancetype)copyWithZone:(NSZone *)zone {
    return _manager;
}

- (instancetype)mutableCopyWithZone:(NSZone *)zone {
    return _manager;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupViews];
}

- (void)setupViews {
    [self setupMap];
    
    [self.locatingButton rounded:(UIRectCornerAllCorners) radius:5];
    @weakify(self)
    [[self.locatingButton rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self onceLocating];
        
    }];
    [self.ensureButton setBackgroundImage:UIColor.blackColor.image forState:(UIControlStateNormal)];
    [self.ensureButton setBackgroundImage:[UIColor.blackColor withAlphaComponent:0.7].image  forState:(UIControlStateHighlighted)];
    [self.ensureButton rounded:(UIRectCornerAllCorners) radius:5];
    
    [[self.ensureButton rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        if (self.completedAction) {
            self.completedAction(self.resultModel);
        }
    }];
}

- (void)setupMap {
    [self insertSubview:self.mapView atIndex:0];
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
}

#pragma mark - 单次定位
- (void)onceLocating {
    [YFLocationManager.shared onceLocating:^(CLLocation * _Nullable location, AMapLocationReGeocode * _Nullable regeocode, NSString * _Nullable error) {
        
        if (regeocode && regeocode.POIName) {
            if (self.locatingSuccessed) {
                self.locatingSuccessed(regeocode.POIName);
            }
        }
        
        if (self.userAnnotation.coordinate.latitude == self.mapView.userLocation.coordinate.latitude &&
            self.userAnnotation.coordinate.longitude == self.mapView.userLocation.coordinate.longitude) {
            
        } else {
            // 位置变动 移除之前添加的用户定位大图钉
            if ([self.mapView.annotations containsObject:self.userAnnotation]) {
                [self.mapView removeAnnotation:self.userAnnotation];
            }
            // 添加大头钉
            self.userAnnotation.coordinate = self.mapView.userLocation.coordinate;
            self.selectedAnnotation.coordinate = self.mapView.userLocation.coordinate;
            self.selectedAnnotation.title = regeocode.POIName;
            
            self.resultModel.city = regeocode.city;
            self.resultModel.latitude = self.mapView.userLocation.coordinate.latitude;
            self.resultModel.longitude = self.mapView.userLocation.coordinate.longitude;
            self.resultModel.POIName = regeocode.POIName;
            
            
            if (regeocode && regeocode.POIName) {
                self.userAnnotation.title = [@"当前位置: " stringByAppendingString:regeocode.POIName];
                self.userAnnotation.subtitle = [NSString stringWithFormat:@"%@%@%@%@%@", regeocode.province, regeocode.city, regeocode.district, regeocode.street, regeocode.number];
                [self.mapView addAnnotation:self.userAnnotation];
            }
        }
        [self.mapView selectAnnotation:self.userAnnotation animated:YES];
        [self.mapView setCenterCoordinate:location.coordinate animated:YES];
    }];
}

#pragma mark --MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    
    if ([annotation isKindOfClass:MAUserLocation.class]) {
        return nil;
    }
    
    if (![annotation isKindOfClass:MAPointAnnotation.class]) {
        return nil;
    }
    static NSString *reuseId = @"ReuseAnnotationId";
    MAAnnotationView *annView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (!annView) {
        annView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
    }
    annView.canShowCallout = YES;
    annView.centerOffset = CGPointMake(0, -18);
    annView.image = [UIImage imageNamed:@"home_store_address30"];
    annView.annotation = annotation;
    
    return annView;
}

- (void)mapViewRequireLocationAuth:(CLLocationManager *)locationManager {
    [locationManager requestAlwaysAuthorization];
}

- (void)mapView:(MAMapView *)mapView mapWillMoveByUser:(BOOL)wasUserAction {
    
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    
}

- (void)setPoi:(AMapPOI *)poi {
    _poi = poi;
    if (poi.name) {
        
        
        self.resultModel.city = poi.city;
        self.resultModel.latitude = poi.location.latitude;
        self.resultModel.longitude = poi.location.longitude;
        self.resultModel.POIName = poi.name;
        
         // 移除除用户定位外的大头钉
        if ([self.mapView.annotations containsObject:self.selectedAnnotation]) {
            [self.mapView removeAnnotation:self.selectedAnnotation];
        }
        
        self.selectedAnnotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
        self.selectedAnnotation.title = poi.name;
        self.selectedAnnotation.subtitle = [NSString stringWithFormat:@"%@%@%@%@", poi.province, poi.city, poi.district, poi.address];

        [self.mapView addAnnotation:self.selectedAnnotation];
        [self.mapView selectAnnotation:self.selectedAnnotation animated:YES];
        [self.mapView setCenterCoordinate:self.selectedAnnotation.coordinate animated:YES];
       
    }
}

#pragma mark - Lazy Load
- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        _mapView.frame = self.bounds;
        _mapView.zoomLevel = 17;
        _mapView.delegate = self;
        _mapView.distanceFilter = 15;
        _mapView.zoomEnabled = YES;
        _mapView.scrollEnabled = YES;
        [_mapView updateUserLocationRepresentation:self.represent];
    }
    return _mapView;
}
- (MAPointAnnotation *)userAnnotation {
    if (!_userAnnotation) {
        _userAnnotation = MAPointAnnotation.new;
    }
    return _userAnnotation;
}

- (MAPointAnnotation *)selectedAnnotation {
    if (!_selectedAnnotation) {
        _selectedAnnotation = MAPointAnnotation.new;
    }
    return _selectedAnnotation;
}
- (YFMapSearchModel *)resultModel {
    if (!_resultModel) {
        _resultModel = [[YFMapSearchModel alloc] init];
    }
    return _resultModel;
}
-(MAUserLocationRepresentation *)represent {
    if (!_represent) {
        _represent = [[MAUserLocationRepresentation alloc] init];
        _represent.showsAccuracyRing = NO;
        _represent.showsHeadingIndicator = NO;
        _represent.image = [UIImage new];
    }
    return _represent;
}

@end
